class RawdataController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, ngDialog, dialogService, ScoreService, getCpList, iRunner, getRaceDetail){

        var vm = this;

        vm.$rootScope    = $rootScope;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.$state        = $state;
        vm.ngDialog      = ngDialog;
        vm.dialogService = dialogService;
        vm.ScoreService  = ScoreService;
        vm.getCpList     = getCpList;
        vm.iRunner       = iRunner;
        vm.getRaceDetail = getRaceDetail;

        // 计时点列表
        vm.getCpList.code==0&&(vm.cplist = vm.getCpList.data);
        
        // 表单数据初始化
        vm.rawdata = {
            bib: '',
            cp: '',
            time: ''
        }

        // 添加比赛开始时间
        vm.rawdata.time = moment(vm.getRaceDetail.data.start_time.substring(0,10))._d;

        // 监听时间变化
        $scope.$watch('rawdata.time', function(newValue, oldValue) {
            if (newValue) {
                angular.element(document.getElementsByName('time')).removeAttr("style")
            }
        });

        // 提交表单
        vm.submitForm = function(isValid) {

            // 验证失败, 提示用户
            if (!isValid) {
                if (!vm.rawdata.bib) {
                    $.blink(angular.element(document.getElementsByName('bib')), 5, 100)
                } else if (!vm.rawdata.cp) {
                    $.blink(angular.element(document.getElementsByName('cp')), 5, 100)
                } else if (!vm.rawdata.time) {
                    $.blink(angular.element(document.getElementsByName('time')), 5, 100)
                }
            }

            // 验证通过
            if (isValid) {

                // 拼接POST数据格式
                var params = {
                    bib: vm.rawdata.bib,
                    cp_index: vm.rawdata.cp.cp_index,
                    time: moment(vm.rawdata.time).format('YYYY-MM-DD HH:mm:ss')
                }

                console.log(params)

                // 新增数据
                vm.ScoreService.postRawdataCreate(params, vm.$cookieStore.get('access_token'), vm.$state.params.race_id)
                .then(function(data) {

                    // 成功调用，更新列表
                    data.code==0&&vm.dialogService.success('创建成功', 'dashboard.race.rawdatalist');

                    // 调用失败, 提示用户
                    (data.code!=0&&data.code!=-1001)&&vm.dialogService.error(data.message);

                    // 登录信息已过期, 请重新登录
                    data.code==-1001&&vm.dialogService.error(data.message, true);

                    console.log(data)

                }, function(data) {
                    console.log('error')
                }); 

            }

            return false;
        }

    }
}

RawdataController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', 'ngDialog', 'dialogService', 'ScoreService', 'getCpList', 'iRunner', 'getRaceDetail']; 

export default RawdataController;